package com.heima.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    @Autowired
    private AdUserMapper adUserMapper;

    /**
     * 后台管理端登录功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {

        //判断参数
        if (!StringUtils.isBlank(dto.getName()) && !StringUtils.isBlank(dto.getPassword())) {

            //1查询用户
            LambdaQueryWrapper<AdUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AdUser::getName, dto.getName());
            AdUser adUser = adUserMapper.selectOne(lambdaQueryWrapper);
            if (adUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //2.手动加盐对比密码
            //数据库密码和盐
            String dbPassword = adUser.getPassword();
            String dbSalt = adUser.getSalt();

            String password = dto.getPassword();
            password = DigestUtils.md5DigestAsHex((password + dbSalt).getBytes());
            if (!password.equals(dbPassword)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //3 返回带token的数据
            //生成token
            String token = AppJwtUtil.getToken(adUser.getId().longValue());
            //隐藏用户信息
            adUser.setSalt("");
            adUser.setPassword("");

            Map<String, Object> map = new HashMap();
            map.put("user", adUser);
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
    }
}
